<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\Article;
use App\Models\Type;
use App\Models\Tag;
use App\Models\Cases;


class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $type_id = 0)
    {		
		// 以前不采用模型关联的2B做法
// 		$data = DB::table('articles as a')
// 		->select(DB::raw('a.*,b.name as type_name'))
// 		->leftJoin('types as b', 'a.type_id', '=', 'b.id')
// 		->where(function($query) use ($request){
// 			if(!empty($request->type_id)){
// 				$query->where('a.type_id', $request->type_id);
// 			}
// 		})
// 		->orderBy('a.id', 'desc')
// 		->paginate(10);

		$type = new Type;
        $typeData = $type->getType();
		$typeData = $type->typeTree($typeData);
		$caseData = (new Cases())->getCase();
		
		$model = new Article;
		$data = $model
		->where(function($query) use ($request){
			if(!empty($request->type_id)){
				$query->where('articles.type_id', $request->type_id);
			}
			if(!empty($request->title)){
				$query->where('articles.title', 'LIKE','%'.trim($request->title).'%');
			}
			if(!empty($request->time1)){
				$query->where('articles.addtime', '>=', strtotime($request->time1));
			}
            if(!empty($request->time2)){
                $query->where('articles.addtime', '<', strtotime($request->time2) + 86400);
            }
            if(!empty($request->flag)){
                $query->whereRaw("FIND_IN_SET(\"$request->flag\",flag)");
//                $query->whereRaw("$request->flag", 'FIND_IN_SET','flag');
            }
			if(!empty($request->case)){
				$query->where('articles.case_id', $request->case_id);
			}
		})
		->orderBy('articles.id', 'desc')
		->paginate(10);
		
		// 给分页追加查询参数
		
		$data = $data->appends(['type_id' => $request->input('type_id'),'title' => $request->input('title'),'time1' => $request->input('time1'),'time2' => $request->input('time2')]);
		$assign = compact('data','request','typeData','caseData');
		return view('admin/article/index',$assign);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
	public function create(Request $request, $typeid = 0)
	{
        $type = new Type;
        $typeData = $type->getType();
        $typeData = $type->typeTree($typeData);
		$tag = new Tag;
		$tagData = $tag->getTag();
		$case = new Cases();
		$caseData = $case->getCase();
		return view('admin/article/add')->with('type_id', $typeid)->with('typeData', $typeData)->with('tagData', $tagData)->with('caseData',$caseData);
	}

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		$this->validate($request, [
			'title' => 'required',
			'type' => 'required',
		],[
			'title.required' => '标题不能为空',
			'type.required' => '正文类型不能为空',
		]);
		
		$model = new Article;
		// 获取tags_id数组
		$article = new Tag;
		$tags_id = $article->getTagId($request->tags);
		
		// $tags = explode(",", $request->tags);
		// dd($tag_id);

		$data = $request->except(['_token','tags','file_img','makerdown-html-code','case_name']);
        // 设置flag标记
        if(!empty($data['flag'])){
            $data['flag'] = implode(",", $data['flag']);
        }
		$data['user_id'] = !empty(session('user_id')) ? session('user_id') : "0";
		$data['addtime'] = time();

		foreach($data as $k=>$v){
			$model->$k = $v;
		}
        $model->keywords = empty($data['keywords']) ? $data['title'] : $data['keywords'];
        $description = _substr($data['body'],255);
        $model->description = empty($data['description']) ? $description : $data['description'];
		$model->user_id = session("info")["id"];
		if($model->save()){
			$model->tags()->sync($tags_id);
			return redirect('/admin/article/index?type_id=' . $data['type_id']);
		}
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $type = new Type;
        $typeData = $type->getType();
        $typeData = $type->typeTree($typeData);
		$tag = new Tag;
		$tagData = $tag->getTag();
		$case = new Cases();
		$caseData = $case->getCase();
		$model = new Article;
		// $olddata = DB::table('articles')->find($id);
		$olddata = $model->find($id);
		// 获取文章标签
		$tags = $olddata->tags->toArray();
		$tags_name = [];
		foreach ($tags as $key => $value) {
		    $tags_name[] = $value['name'];
		}
		$tags_name = implode(',', $tags_name);
		$assign = compact('olddata', 'typeData', 'tagData', 'tags_name', 'caseData');
		return view("admin/article/edit", $assign);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
		// 表单验证
		$this->validate($request, [
			'title' => 'required',
			'body' => 'required',
		],[
			'title.required' => '标题不能为空',
			'body.required' => '内容不能为空',
		]);
		$model = new Article;
		$data = $request->except(['_token','tags','file_img','case_name']);
        // 设置flag标记
        if(!empty($data['flag'])){
            $data['flag'] = implode(",", $data['flag']);
        }
		$article = $model->find($id);
		foreach($data as $k=>$v){
			$article->$k = $v;
		}
        // 如果没有缩略图就去内容中找第一张图保存为缩略图
        if(empty($data['picname'])){
            //
            $article->picname = _getImg($data['body']);
        }
		if ($article->save()) {
			// 获取tags_id数组
			$Tag = new Tag;
			$tags_id = $Tag->getTagId($request->tags);
			$article->tags()->sync($tags_id);
		    return redirect('/admin/article/index');
		} else {
		    return redirect('/admin/article/edit/'.$id);
		}
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
		DB::table('articles')->where('id', '=', $id)->delete();
		return redirect('/admin/article/index');
    }
	
	/**
	 * 批量删除
	 */
	public function dels(Request $request)
	{
		if($ids = $request->input('ids')){
			DB::table('articles')->whereIn('id', $ids)->delete();
		}
		return redirect('/admin/article/index');
	}
}
